package cate.game.pvp.pointrace.handler;

import cate.game.pvp.pointrace.data.PointRacePs;
import cate.game.pvp.pointrace.data.PointRacePsData;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;

import static cate.game.pvp.pointrace.data.PointRacePs.INDEX_NAME;
import static cate.game.pvp.pointrace.data.PointRacePs.INDEX_PLAYER;

public class BothPointRacePsOperation implements PointRacePsOperation {

    private final PointRacePsData psData;

    public BothPointRacePsOperation(Supplier<PointRacePsData> psDataSupplier) {
        Objects.requireNonNull(psDataSupplier);
        this.psData = Objects.requireNonNull(psDataSupplier.get());
    }

    @Override
    public String update(PointRacePs ps) {
        Map<String, PointRacePs> playerIndexMap = psData.getIndex(INDEX_NAME);
        PointRacePs ops = playerIndexMap.get(ps.getUid());
        if (Objects.nonNull(ops) && StringUtils.equalsIgnoreCase(ps.getCps().getMd5Sum(), ops.getCps().getMd5Sum())) {
            return ps.getCps().getMd5Sum();
        }
        if (Objects.nonNull(ops)) {
            ps.getOpponent().setPoints(ops.getOpponent().getPoints());
        }
        psData.addValue(ps.getIndexName(), ps);
        psData.addIndex(INDEX_NAME, ps.getIndexName(), ps);
        psData.addIndex(INDEX_PLAYER, ps.getIndexName(), ps);
        return ps.getCps().getMd5Sum();
    }

    @Override
    public PointRacePs findOne(String uid) {
        return this.psData.getIndex(INDEX_NAME).get(uid);
    }

    @Override
    public void updatePoints() {
        Map<String, PointRacePs> indexMap = psData.getIndex(INDEX_PLAYER);
        if (Objects.nonNull(indexMap) && !indexMap.isEmpty()) {
            indexMap.values()
                    .stream()
                    .map(PointRacePs::getOpponent)
                    .forEach(opp -> opp.setPoints(Math.max(1000L, (long) (opp.getPoints() * 0.7))));
        }
    }
}
